<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author XPF
-->
<template>
  <BasicDrawer v-bind="$attrs" :showFooter="true" :okAuth="'physical:exercisePrescription:edit'"
    @register="registerDrawer" @ok="handleSubmit" width="60%">
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #remarks="{ model, field }">
        <WangEditor v-model:value="model[field]" :bizKey="record.id" :bizType="'testDataChild_' + field" :height="300" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
export default defineComponent({
  name: 'ViewsPhysicalExercisePrescriptionForm',
});
</script>
<script lang="ts" setup>
import { defineComponent, ref, computed } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { Icon } from '/@/components/Icon';
import { BasicForm, FormSchema, useForm } from '/@/components/Form';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import {
  ExercisePrescription,
  exercisePrescriptionSave,
  exercisePrescriptionForm,
} from '/@/api/physical/exercisePrescription';
import { json } from 'stream/consumers';
import { WangEditor } from '/@/components/WangEditor';

const emit = defineEmits(['success', 'register']);

const { t } = useI18n('physical.exercisePrescription');
const { showMessage } = useMessage();
const record = ref<ExercisePrescription>({} as ExercisePrescription);
const media = ref({});
const image = ref({});

const getTitle = computed(() => ({
  icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
  value: record.value.isNewRecord ? t('新增运动处方库') : t('编辑运动处方库'),
}));

const inputFormSchemas: FormSchema[] = [
  {
    label: t('处方名称'),
    field: 'prescriptionName',
    component: 'Input',
    componentProps: {
      maxlength: 200,
    },
    required: true,
  },
  {
    label: t('处方分类'),
    field: 'prescriptionType',
    component: 'CheckboxGroup',
    componentProps: {
      dictType: 's_prescription_type',
      allowClear: true,
    },
    required: true,
  },
  {
    label: t('适配年级'),
    field: 'adaptGrade',
    component: 'CheckboxGroup',
    componentProps: {
      dictType: 'vke_grade',
      allowClear: true,
      mode: 'multiple',
    },
    required: true,
  },
  {
    label: t('处方视频'),
    field: 'prescriptionVideoPath',
    component: 'Upload',
    componentProps: ({ formModel }) => {
      return {
        maxNumber: 1,
        uploadType: 'media',
        bizType: 'prescriptionVideo',
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        onChange: (file: ChangeEvent) => {
          console.log(file);
          // console.log(file[0].fileUrl);
          // console.log(formModel.prescriptionVideoPath);
          formModel.prescriptionVideoPath = file[0].fileUrl;
        },
      };
    },
    required: true,
  },
  // {
  //   label: t('处方视频路径'),
  //   field: 'prescriptionVideoPath',
  //   component: 'Input',
  //   componentProps: {
  //     disabled: true,
  //   },
  // },
  {
    label: t('处方视频封面'),
    field: 'thumbnailPath',
    component: 'cover',
    componentProps: {
      maxNumber: 1,
      uploadType: 'image',
      bizType: 'thumbnail',
      loadTime: computed(() => record.value.__t),
      bizKey: computed(() => record.value.id),
      onChange: (file: ChangeEvent) => {
        console.log(file);
        image.value = file;
      },
    },
  },
  {
    label: t('动作要领'),
    field: 'prescriptionExplanation',
    component: 'InputTextArea',
    required: true,
    slot: 'remarks',
    colProps: { lg: 24, md: 24 },
  },
  {
    label: t('排序'),
    field: 'sort',
    component: 'Input',
    componentProps: {
      maxlength: 50,
    },
  },
];

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 120,
  schemas: inputFormSchemas,
  baseColProps: { lg: 24, md: 24 },
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({ loading: true });
  const res = await exercisePrescriptionForm(data);
  console.log(res);
  if (res.exercisePrescription.thumbnailPath) {
    image.value = {
      fileUrl: res.exercisePrescription.thumbnailPath,
        fileEntity: {
        id: res.exercisePrescription.thumbnailId,
      },
    };
  }else {
      image.value = {};
  };
  // media.value = {
  //   fileUrl: res.exercisePrescription.prescriptionVideoPath,
  //   fileEntity: {
  //     id: res.exercisePrescription.prescriptionVideoPathId,
  //   },
  // };
  // res.exercisePrescription.prescriptionVideoPath = {
  //   prescriptionVideoPathId: res.exercisePrescription.prescriptionVideoPathId,
  // };
  res.exercisePrescription.id = res.exercisePrescription.prescriptionVideoPathId;
  console.log(res.exercisePrescription);
  record.value = (res.exercisePrescription || {}) as ExercisePrescription;
  record.value.__t = new Date().getTime();
  record.value.sort = record.value.sort ? record.value.sort : 1;
  setFieldsValue(record.value);
  setDrawerProps({ loading: false });
});

async function handleSubmit() {
  try {
    const data = await validate();
    setDrawerProps({ confirmLoading: true });
    const params: any = {
      isNewRecord: record.value.isNewRecord,
      prescriptionId: record.value.prescriptionId,
    };
    console.log(data.thumbnailPath);
    if (!data.thumbnailPath) {
      data.thumbnailPath =
        'http://106.14.199.2:37091/test4vke/fileupload/202309/1707236205759131648.jpg?response-content-type=image%2Fjpeg&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=5zQt0xkADWtm05Ad%2F20230928%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230928T033228Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=c8eb340e1fcbfacbaf14a6a0234de9dd884afde040b66bded0f5f5b7b12a8b0f';
        data.thumbnailId = '1707236807060361216';
    }
    // if (JSON.stringify(media.value) != '{}') {
    //   data.prescriptionVideoPath = media.value.fileUrl;
    //   data.prescriptionVideoPathId = media.value.fileEntity.id;
    // }
    console.log(JSON.stringify(image.value));
    if (JSON.stringify(image.value) != '{}') {
      data.thumbnailPath = image.value.fileUrl;
      data.thumbnailId = image.value.fileEntity.id;
    }
    // console.log('submit', params, data, record, media.value);
    const res = await exercisePrescriptionSave(params, data);
    showMessage(res.message);
    setTimeout(closeDrawer);
    emit('success', data);
  } catch (error: any) {
    if (error && error.errorFields) {
      showMessage(t('您填写的信息有误，请根据提示修正。'));
    }
    console.log('error', error);
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
